package com.fan.shop.dao;

import java.util.List;

import javax.inject.Named;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import com.fan.shop.domain.TransactionReference;

@Named("transactionReferenceDao")
public class TransactionReferenceDaoImpl implements TransactionReferenceDao {

	private SessionFactory sessionFactory;

	/**
	 * Get Hibernate Session Factory
	 * 
	 * @return SessionFactory - Hibernate Session Factory
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * Set Hibernate Session Factory
	 * 
	 * @param SessionFactory
	 *            - Hibernate Session Factory
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@SuppressWarnings("unchecked")
	public List<TransactionReference> getAllTransactionReferences() {
		List<TransactionReference> list = getSessionFactory()
				.getCurrentSession().createQuery("from TransactionReference")
				.list();
		return list;
	}

	public TransactionReference getTransactionReference(String name) {
		TransactionReference transactionReference = (TransactionReference) getSessionFactory()
				.getCurrentSession().get(TransactionReference.class, name);
		return transactionReference;
	}

	public boolean hasTransactionReference(String name) {
		if (getTransactionReference(name) != null) {
			return true;
		} else {
			return false;
		}
	}

	public int getSize() {
		return getAllTransactionReferences().size();
	}

	public void addTransactionReference(
			TransactionReference transactionReference) {
		getSessionFactory().getCurrentSession().save(transactionReference);
	}

	public void updateTransactionReference(
			TransactionReference transactionReference) {
		getSessionFactory().getCurrentSession().update(transactionReference);
	}

	public void deleteTransactionReference(
			TransactionReference transactionReference) {
		getSessionFactory().getCurrentSession().delete(transactionReference);
	}

	@SuppressWarnings("unchecked")
	public List<String> getColumnNames() {
		List<String> columns = sessionFactory
				.getCurrentSession()
				.createSQLQuery(
						"SELECT COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TRANSACTION_REFERENCE'")
				.list();

		return columns;
	}

	@SuppressWarnings("unchecked")
	public List<TransactionReference> getListByGroup(String code) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(TransactionReference.class);
		criteria.add(Restrictions.eq("groupCode", code));
		List<TransactionReference> list = criteria.list();
		return list;
	}

}
